﻿using ASmile.Com;
using ASmile.Extend;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ASmile.Win
{
    public class TokenHelper
    {
        static TokenHelper()
        {
            RefreshTokenTask();
        }

        /// <summary>
        /// 获取token值
        /// </summary>
        public static string TokenValue { get; private set; }
        /// <summary>
        /// 最后一个token值，切换用户时，先返回一个只有登陆权限的token，选择角色之后再替换，切换取消则恢复
        /// </summary>
        static string LastToken { get; set; }

        static void RefreshTokenTask()
        {
            Task.Factory.StartNew(() =>
            {
                LogHelper.LogObj.Info("开始刷新Token任务-WebApiClient");
                //WebApiClient bll = new WebApiClient();
                var tokenURL = Config.Settings.RefreshTokenUrl;
                var tokenName = Config.Settings.TokenName;
                var rootURL = Config.Settings.ServerUrl;

                var webApi = new WebApiClient(rootURL);
                while (true)
                {
                    Thread.Sleep(TimeSpan.FromMinutes(Config.Settings.RefreshTokenMinutes));
                    try
                    {
                        if (TokenValue.IsNotEmpty())
                        {
                            webApi.SetHttpHeader(tokenName, TokenValue);
                            var r = webApi.PostRequest<ApiResult<UserLoginRet>>(tokenURL, null);
                            if (r)
                            {
                                var data = r.data;
                                string newToken = data.Token;
                                if (!newToken.StringEquals(TokenValue))
                                {
                                    TokenValue = newToken;
                                    LogHelper.LogObj.Info("Token 更新了");
                                }
                            }
                            else
                            {
                                if (r.code != 101)
                                {
                                    LogHelper.LogObj.Info($"刷新Token失败,code: {r.code},msg: {r.msg}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogObj.Error("自动刷新token时发生异常", ex);
                    }
                }
            });
        }

        public static void SetToken(string token)
        {
            LastToken = TokenValue;
            TokenValue = token;
        }
        /// <summary>
        /// 恢复到上次的token
        /// </summary>
        public static bool ResetToken()
        {
            if (LastToken.IsEmpty()) return false;
            TokenValue = LastToken;
            return true;
        }
    }
}
